import Vue from 'vue'
import Vuex from 'vuex'

import axios from 'axios'

Vue.use(Vuex)

const state = {
    isFirst: true,
    isLoading: false,
    isError: '',
    cards: []
}

const mutations = {
    REQ_FIRST(state) {
        state.isFirst = false
        state.isLoading = true
    },
    RES_LAST(state,err) {
        state.isLoading = false
        state.isError = err
    },
    NEWCARDS(state, newCards) {
        state.isLoading = false
        state.cards = newCards
    }

}

const actions = {

    async getCards({ commit }, keyword) {
        try {
            // 修改 isFirst isLoading 状态
            commit('REQ_FIRST')
            // 发送请求
            const { data: { items } } = await axios({
                url: 'https://api.github.com/search/users',
                params: {
                    q: keyword
                }
            })

            const newCards = items.map(item => ({
                id: item.id,
                login: item.login,
                url: item.url,
                avatar_url: item.avatar_url
            })
            )
            // 修改state中的数据
            commit('NEWCARDS', newCards)
        } catch (error) {
            commit('RES_LAST', error.message)
        }
    }
}

const getters = {

}

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
})